package indi.woniu.security.filter;

import indi.woniu.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: GaN601
 * @Date: 2021/12/22 22:52
 * @Description:
 */
public class JwtAuthenticationTokenFilter extends BasicAuthenticationFilter {
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private Logger logger;
    
    @Override
    protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
            final FilterChain chain) throws IOException, ServletException {
        String authHeader = request.getHeader("token");
        
        String bearer = "Bearer ";
        if (authHeader != null && authHeader.startsWith(bearer)) {
            final String authToken = authHeader.substring(bearer.length());
            
            //从token中获取用户信息，jwtUtils自定义的token加解密方式
            String username = null;
            try {
                Claims claims = jwtUtils.parseJwt(authToken);
                username = claims.getSubject();
            } catch (ExpiredJwtException e) {
                logger.error("Token异常::", e);
            }
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                //根据用户名获取用户对象
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                
                if (userDetails != null) {
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(userDetails, null,
                                    userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    //设置为已登录
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
            
        }
        
        chain.doFilter(request, response);
    }
    
    public JwtAuthenticationTokenFilter(
            final AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }
    
    public JwtAuthenticationTokenFilter(
            final AuthenticationManager authenticationManager,
            final AuthenticationEntryPoint authenticationEntryPoint) {
        super(authenticationManager, authenticationEntryPoint);
    }
}
